import {
  getNewCartGoods,
  mergeCart,
  findCartList,
  insertCart,
  deleteCart,
  updateCart,
  checkAllCart
} from '@/api/cart'

// 购物车模块
export default {
  namespaced: true,
  state: () => {
    return {
      list: []
    }
  },
  getters: {
    // 有效商品列表
    validList (state) {
      return state.list.filter(item => item.stock > 0 && item.isEffective)
    },
    // 有效商品件数
    validTotal (state, getters) {
      // console.log('---validTotal---', getters)
      return getters.validList.reduce((p, c) => p + c.count, 0)
    },
    // 有效商品总金额
    validAmount (state, getters) {
      return (
        getters.validList.reduce((p, c) => p + c.nowPrice * 100 * c.count, 0) /
        100
      )
    },
    // 无效商品列表
    invalidList (state) {
      return state.list.filter(item => !(item.stock > 0 && item.isEffective))
    },
    // 选中商品列表
    selectedList (state, getters) {
      return getters.validList.filter(item => item.selected)
    },
    // 选中商品件数
    selectedTotal (state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },
    // 选中商品总金额
    selectedAmount (state, getters) {
      return (
        getters.selectedList.reduce(
          (p, c) => p + c.nowPrice * 100 * c.count,
          0
        ) / 100
      )
    },
    // 是否全选
    isCheckAll (state, getters) {
      return (
        getters.validList.length === getters.selectedList.length &&
        getters.selectedList.length !== 0
      )
    }
  },
  mutations: {
    // 设置购物车列表
    setCart (state, payload) {
      state.list = payload
    },
    // 本地：id skuId name picture price nowPrice count attrsText selected stock isEffective
    addCart (state, payload) {
      const findIndex = state.list.findIndex(
        goods => goods.skuId === payload.skuId
      )
      if (findIndex > -1) {
        // 找到了
        payload.count += state.list[findIndex].count
        // 把之前存在的删除掉
        state.list.splice(findIndex, 1)
      }

      state.list.unshift(payload)
    },
    // 修改购物车商品
    updateCart (state, goods) {
      // goods中字段有可能不完整，goods有的信息才去修改。
      // 1. goods中必需又skuId，才能找到对应的商品信息
      const updateGoods = state.list.find(item => item.skuId === goods.skuId)
      for (const key in goods) {
        if (
          goods[key] !== null &&
          goods[key] !== undefined &&
          goods[key] !== ''
        ) {
          updateGoods[key] = goods[key]
        }
      }
    },
    deleteCart (state, paylod) {
      const findIndex = state.list.findIndex(goods => goods.skuId === paylod)

      if (findIndex > -1) {
        state.list.splice(findIndex, 1)
      }
    }
  },
  actions: {
    // 异步加入购物车
    asyncAddCart ({ rootState, commit }, payload) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 登录了
          insertCart(payload)
            .then(() => {
              return findCartList()
            })
            .then(({ result }) => {
              commit('setCart', result)
              resolve()
            })
        } else {
          // 未登录
          commit('addCart', payload)
          resolve()
        }
      })
    },
    // 异步获取购物车列表
    findCartList ({ rootState, state, commit }) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 登录 TODO
          findCartList().then(({ result }) => {
            commit('setCart', result)
          })
        } else {
          // 本地
          // Promise.all() 可以并列发送多个请求，等所有请求成功，调用then
          // Promise.race() 可以并列发送多个请求，等最快的请求成功，调用then
          // 传参事promise数组
          const promiseArr = state.list.map(item => {
            return getNewCartGoods(item.skuId)
          })

          Promise.all(promiseArr)
            .then(dataList => {
              dataList.forEach((data, i) => {
                commit('updateCart', {
                  skuId: state.list[i].skuId,
                  ...data.result
                })
              })
              resolve()
            })
            .catch(err => reject(err))
        }
      })
    },
    // 异步删除购物车
    asyncDeleteCart ({ rootState, commit }, payload) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 登录了
          deleteCart([payload])
            .then(() => {
              return findCartList()
            })
            .then(({ result }) => {
              commit('setCart', result)
              resolve()
            })
        } else {
          // 未登录
          commit('deleteCart', payload)
          resolve()
        }
      })
    },
    // 批量删除选中商品
    asyncBatchDeleteCart (ctx, isClear) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录 TODO
          const ids = ctx.getters[isClear ? 'invalidList' : 'selectedList'].map(
            item => item.skuId
          )

          // 登录了
          deleteCart(ids)
            .then(() => {
              return findCartList()
            })
            .then(({ result }) => {
              ctx.commit('setCart', result)
              resolve()
            })
        } else {
          // 本地
          // 1. 获取选中商品列表，进行遍历调用deleteCart mutataions函数
          ctx.getters[isClear ? 'invalidList' : 'selectedList'].forEach(
            item => {
              ctx.commit('deleteCart', item.skuId)
            }
          )
          resolve()
        }
      })
    },
    // 修改购物车中的商品
    asyncUpdateCart ({ rootState, commit }, payload) {
      // payload中，必须要有skuId，其它想要修改的属性 selected count
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 登录了
          updateCart(payload)
            .then(() => {
              return findCartList()
            })
            .then(({ result }) => {
              commit('setCart', result)
              resolve()
            })
        } else {
          commit('updateCart', payload)
          resolve()
        }
      })
    },
    // 全选 & 取消全选
    asyncCheckAllCart ({ rootState, getters, commit }, payload) {
      // payload中，必须要有skuId，其它想要修改的属性 selected count
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 登录了
          const ids = getters.validList.map(item => item.skuId)
          checkAllCart({ selected: payload, ids })
            .then(() => {
              return findCartList()
            })
            .then(({ result }) => {
              commit('setCart', result)
              resolve()
            })
        } else {
          // 本地
          // 1. 获取有效的商品列表，遍历的去调用修改mutations即可
          getters.validList.forEach(item => {
            commit('updateCart', { skuId: item.skuId, selected: payload })
          })
          resolve()
        }
      })
    },
    // 更改购物车中的商品规格
    asyncUpdateCartSku ({ rootState, state, commit }, payload) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 登录了
          // 1. 获取原先商品的数量
          const { oldSkuId, currSku } = payload
          // 找出之前的sku
          const oldSku = state.list.find(item => item.skuId === oldSkuId)
          // 2. 删除原先商品
          deleteCart([oldSkuId])
            .then(() => {
              return insertCart({ skuId: currSku.skuId, count: oldSku.count })
            })
            .then(() => {
              return findCartList()
            })
            .then(({ result }) => {
              commit('setCart', result)
              resolve()
            })
          // 3. 获取修改的skuId 和 原先商品数量 做一个加入购物车操作
          // 4. 更新列表
        } else {
          // 未登录，本地操作
          const { oldSkuId, currSku } = payload
          // 找出之前的sku
          const oldSku = state.list.find(item => item.skuId === oldSkuId)
          // 删除之前的sku
          commit('deleteCart', oldSkuId)
          // 构建新的sku对象
          const {
            skuId,
            price: nowPrice,
            inventory: stock,
            specsText: attrsText
          } = currSku
          const newSku = { ...oldSku, skuId, nowPrice, stock, attrsText }

          // 加入到购物车中
          commit('addCart', newSku)
        }
      })
    },
    // 登录后合并本地购物车
    asyncMergeCart ({ commit, getters }) {
      return new Promise((resolve, reject) => {
        // 准备好要提交给后台的购物车数据
        const cartList = getters.validList.map(({ skuId, selected, count }) => {
          return { skuId, selected, count }
        })

        mergeCart(cartList).then(() => {
          // 合并成功后将本地购物车删除
          commit('setCart', [])

          resolve()
        })
      })
    }
  }
}
